<?php
class My_Plugin_Module extends Zend_Controller_Plugin_Abstract
{
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {        
		$module = $request->getModuleName();
        $layout = Zend_Layout::getMvcInstance();
        // check module and automatically set layout
        $layoutsDir = $layout->getLayoutPath();

        // check if module layout exists else use default
        $userLayout = '';
        
        if(is_file(CONFIG_PATH . '/layout.ini')){
	    	$layoutConf = new Zend_Config_Ini(CONFIG_PATH . '/layout.ini', APPLICATION_ENV);
                        	    	
	    	$moduleParsed = strtolower($module).'Module';      
	    	$controllerParsed = strtolower($request->getControllerName()).'Controller';
	    	$actionParsed = strtolower($request->getActionName()).'Action';
            
	       	if(isset($layoutConf->resources->$moduleParsed->$controllerParsed->$actionParsed->layout)){
	    		if(is_file($layoutsDir . DIRECTORY_SEPARATOR . $layoutConf->resources->$moduleParsed->$controllerParsed->$actionParsed->layout.'.phtml')){
	    			$userLayout = $layoutConf->resources->$moduleParsed->$controllerParsed->$actionParsed->layout;
	    		}
    		}elseif(isset($layoutConf->resources->$moduleParsed->$controllerParsed->layout)){
	    		if(is_file($layoutsDir . DIRECTORY_SEPARATOR . $layoutConf->resources->$moduleParsed->$controllerParsed->layout.'.phtml')){
	    			$userLayout = $layoutConf->resources->$moduleParsed->$controllerParsed->layout;
	    		}
    		}
        }
        
		if(!isset($userLayout[0])){
			if(is_file($layoutsDir . DIRECTORY_SEPARATOR . $module . ".phtml")){
				$userLayout = $module;
			}else{
				$userLayout = 'default';
			}
		}               
        $layout->setLayout($userLayout);
    }
}